Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

requires to access .default after build while it's not required in dev (CJS dependency) #2139

Closed
songquanpeng opened this issue Feb 21, 2021 · 122 comments
Labels
bug: upstream Bug in a dependency of Vite has workaround inconsistency Inconsistency between dev & build

Comments

@songquanpeng
Copy link

songquanpeng commented Feb 21, 2021

Describe the bug

Encountered “Minified React error” in the production environment, the dev environment is fine.

error: Minified React error #130; visit https://reactjs.org/docs/error-decoder.html?invariant=130&args[]=object&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at vc (vendor.93c27df6.js:23)
    at d (vendor.93c27df6.js:23)
    at vendor.93c27df6.js:23
    at vendor.93c27df6.js:23
    at Ts (vendor.93c27df6.js:23)
    at ul (vendor.93c27df6.js:23)
    at ic (vendor.93c27df6.js:23)
    at tc (vendor.93c27df6.js:23)
    at ql (vendor.93c27df6.js:23)
    at zl (vendor.93c27df6.js:23)

Reproduction

Repo: https://github.com/songquanpeng/snippet-manager/tree/aa02a582c676bd3dcd5254f18d7087bb8a1a7220

My React application is on the web folder.

System Info

  • vite version: 2.0.0
  • Operating System: Windows 10
  • Node version: v14.15.3
  • Package manager (npm/yarn/pnpm) and version: 7.5.4

Summarization of the root problem

#2139 (comment)

@underfin
Copy link
Member

Not encountered this error. Can you have a try after upgrade vite?

@songquanpeng
Copy link
Author

songquanpeng commented Feb 21, 2021

PS D:\Project\Go\snippet-manager\web> vite --version
vite/2.0.1 win32-x64 node-v14.15.3

Dev:
image
Production:
image

@songquanpeng

This comment was marked as outdated.

@haikyuu
Copy link
Contributor

haikyuu commented Mar 19, 2021

I ran into the same issue using latest Vite version.

Note

The title of the issue is very vague as this error is displayed by minified React instead of ANY React error. So it can be anything really.
But in both our cases, this is the actual error Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

The first thing to do in this case is to debug the app in order to have more details: Use minify and dev mode in your vite.config.js in order to get the real issue with the possibility to inspect in the browser dev tools.

export default defineConfig({
  plugins: [reactRefresh()],
  mode: "development",
  build: {
    minify: false,
  }
});

Hacky solution in my case

In my case it was coming from using react-switch. And I hacked it to work using the following (don't tell anyone about this)

import S from "react-switch";
const Switch = S.default? S.default: S
console.log(S); // inspecting

Basically this is the content of the import {__esModule: true, default: ƒ}

The react-switch library is built as cjs so this is probably a cjs compatibility issue for Vite's Rollup build configuration ?

In the reproduction repo

If you follow the debugging steps, you will discover that the culprit in your case is react-highlight
image

Notes for reproduction

In order to reproduce the issue, you need to:

  • Run npx vite build
  • Serve the dist folder using an http server. e.g: npx http-server dist --port 3002

@ntkoopman
Copy link

It's because esbuild is checking for __esModule at runtime and rollup is not. So it will happen to any library that has an entry point with

module.exports = require("./something");

Since this file does not include the 'magic string' __esModule as checked by https://github.com/rollup/plugins/blob/master/packages/commonjs/src/generate-exports.js#L82 it's not converted correctly.

vite dev vite build
import Switch from 'react-switch'; Switch ok
import Switch from 'react-switch'; Switch.default ok
import Switch from 'react-switch/dist/react-switch.dev.js'; Switch ok ok

So need to raise a bug in rollup for this.

@ntkoopman
Copy link

Unsurprisingly, it's a known issue mentioned in rollup/plugins#481 but it doesn't seem like there will be a solution very soon.

One thing to note is that the node behaviour is mutually exclusive with supporting __esModule. When running natively from Node, Switch.default would be the only correct option. In the end the best way would probably to ask the library author to publish an esm version to avoid this problem completely.

@haikyuu
Copy link
Contributor

haikyuu commented Mar 25, 2021

It's because esbuild is checking for __esModule at runtime and rollup is not

Then we should issue a big warning at dev time about this behaviour. It's a critical bug (in the libraries) that affects the Vite experience drastically.

@KannarFr
Copy link

Yup, same problem here: #2692.

@ntkoopman
Copy link

After looking into this some more, I think vite should switch to behave the same as rollup. That way it would be consistent with how node works (and snowpack as well).

For now, importing a commonjs module should probably show a warning somewhere.

@patak-dev
Copy link
Member

@ntkoopman would you expand a bit in what needs to be changed in Vite? A PR would be great so we can discuss what the implications are there (from anyone that is following this issue)

Agree about the warning in the meantime in case that change is not easy to land, PR welcome for that patch too

@ntkoopman
Copy link

So I already changed my mind again, since changing the dev behaviour will still break dependencies. So, the best case would still be that it gets fixed in rollup. I tested with a commonjs plugin I wrote and it seems to work for us for now:

import cjs from 'rollup-plugin-cjs';

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        index: resolve(__dirname, 'src/index.html'),
      },
      plugins: [cjs()],
    },
    commonjsOptions: {
      exclude: [/./],
    },
  },
});

I looked into returning a warning, but decided not to, because if it's possible to detect the issue it should be possible to fix it..

I'll continue on the commonjs plugin and see if I can fix it there (or maybe it's just a configuration option that's missing?) now that I have some unit tests.

@barankyle
Copy link

barankyle commented Apr 22, 2021

Hacky solution in my case

In my case it was coming from using react-switch. And I hacked it to work using the following (don't tell anyone about this)

import S from "react-switch";
const Switch = S.default? S.default: S
console.log(S); // inspecting

Basically this is the content of the import {__esModule: true, default: ƒ}

The react-switch library is built as cjs so this is probably a cjs compatibility issue for Vite's Rollup build configuration ?

I used this to fix this issue cropping up with react-no-ssr.

@Kamyil
Copy link

Kamyil commented May 6, 2021

This issue is complete blocker for me from using Vite in my React production apps.
In my case, the issue does not show up in the development mode (it works completely fine there) and it does only show up in production.
The thing is... since a lot of external React components (like react-switch, react-notfification, react-select) uses export default (unfortunetly) - it forces developer to guess which one of it crashes the app. However, trying setting "development" mode for production build and disabling minifier option doesn't help either, because DevTools also doesn't show me any exact place in the stacktrace where the problem can exist.
Hope this issue will be resolved soon, because I loved using Vite so far 😔

@rememberlenny
Copy link

Is there an ETA on at least catching this some way in development?

@noorvir
Copy link

noorvir commented May 11, 2021

I'm blocked by the same problem. How are people deploying their apps into production? Is there a workaround in the meantime?

@barankyle
Copy link

To track down which package was causing the problem, I had to do some grindy work of setting breakpoints in Chrome dev tools (on the error-throwing lines, and in some cases going up the call stack) and then iterating through until I found the culprit. Not an easily reproducible solution, especially since in most cases you're dealing with minified code.

@vikbert

This comment was marked as off-topic.

@flasco

This comment was marked as off-topic.

@feryrmdhn
Copy link

I have some problem, but I use nextjs with yarn, im not using Vite

any solutions?

@filipw01
Copy link
Contributor

filipw01 commented May 24, 2023

I have some problem, but I use nextjs with yarn, im not using Vite

any solutions?

Nextjs has no connection to vite, so it's a separate issue. I recommend you look for it on nextjs's github or ask for help on some discord server in the future. This issue has a lot of subscribers so it's best not to notify all of them needlessly

One generic workaround is to use interopDefault function like this. I don't know how nextjs handles imports, but that's what's a workaround looks in vite

import exampleImport from 'cjs-package'

export const safeImport = interopDefault(exampleImport)

function interopDefault(value) {
  return value.default ? value.default : value
}

If you have further questions feel free to hit me up on Discord filipw01#2360

@ljharb
Copy link

ljharb commented May 24, 2023

(to be clear this isn't a faulty package, it's how most things on npm work - it's just CJS)

@nghiant96
Copy link

with @mdi/react
Templarian/MaterialDesign-React#69

@jensbodal
Copy link

You shouldn't need this if you're using the vite types: https://vitejs.dev/guide/features.html#client-types

Modified version of the solution to prevent the raises of TS error :

import { createRequire } from 'module';
import { defineConfig } from 'vite';
import type { RollupCommonJSOptions } from '@rollup/plugin-commonjs';

const require = createRequire(import.meta.url);


export default defineConfig({
  build: {
    // Bugfix required to handle issue with vite, rollup and libs (like react-phone-input-2)
    commonjsOptions: {
      defaultIsModuleExports(id) {
        try {
          const module = require(id);
          if (module?.default) {
            return false;
          }
          return 'auto';
        } catch (error) {
          return 'auto';
        }
      },
      transformMixedEsModules: true,
    } as RollupCommonJSOptions,
  },
  // ...
})

You shouldn't need to cast to RollupCommonJSOptions if you're using the vite client types: https://vitejs.dev/guide/features.html#client-types

@DmytroSvarkovskiy
Copy link

DmytroSvarkovskiy commented Jun 3, 2023

Hello. Also encountered error 130 when building the project on Vite. Found such a working solution in the documentation to add the following settings to viteconfig: optimizeDeps: {
include: ['esm-dep > cjs-dep']
}

@r-mauricio
Copy link

This worked. Thank you

@pietmichal
Copy link

#8743 was merged June 24th. I guess this is fixed now, right?

@ad1992
Copy link

ad1992 commented Aug 22, 2023

Any update on this ? I am facing similar issue when using a package with default export https://www.npmjs.com/package/markdown-to-text and changing the export to named export solves the issue.

@bluwy
Copy link
Member

bluwy commented Aug 23, 2023

Are you hitting this issue for browser or SSR? I know there's still the inconsistency in SSR (which I want to look into for Vite 5), but I'm not sure about browsers if the comment above mentioned #8743 fixes it?

@ad1992
Copy link

ad1992 commented Aug 23, 2023

@ljharb I am facing the issue in browser. Changing the above mentioned library to named export fixes the issue. I am using vite version 4.4.2

@callumbuttery
Copy link

callumbuttery commented Sep 3, 2023

Updating vite to 4.4.9 has fixed this for me

@NMinhNguyen
Copy link
Contributor

Are you hitting this issue for browser or SSR? I know there's still the inconsistency in SSR (which I want to look into for Vite 5), but I'm not sure about browsers if the comment above mentioned #8743 fixes it?

I can actually confirm that [email protected] (which includes rollup/plugins#1455) fixes this issue in the browser for me (haven't tried SSR). I've tried various packages with default exports such as react-csv-reader and the aforementioned markdown-to-text.

See also

@bluwy
Copy link
Member

bluwy commented Oct 29, 2023

I've tried all the repros and packages mentioned here and I cannot reproduce the issue today (Vite 4.5.0). I'll close this as fixed. If you still see the issue, please leave a comment with a repro, or open a new issue. Thanks!

@bluwy bluwy closed this as completed Oct 29, 2023
@BarneyRoos
Copy link

BarneyRoos commented Oct 29, 2023 via email

@github-actions github-actions bot locked and limited conversation to collaborators Nov 13, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug: upstream Bug in a dependency of Vite has workaround inconsistency Inconsistency between dev & build
Projects
Archived in project
Development

Successfully merging a pull request may close this issue.